﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using Library;

namespace Sport_Shop
{
    public partial class Giohang : System.Web.UI.Page
    {
        static DataTable tbGioHang = new DataTable();
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                load_ListSanpham();
                get_ngay();
            }
        }

        private void load_ListSanpham()
        {
            try
            {
                if (Request.QueryString["TenSP"] != null)
                {
                    string tensp = Request.QueryString["TenSP"].ToString();
                    DataAccess da = new DataAccess();
                    string sql = "SELECT DonGia FROM SanPham WHERE TenSP = '" + tensp + "'";
                    DataTable dt = da.GetDataList(sql).Tables[0];

                    int dongia = int.Parse(dt.Rows[0][0].ToString());
                    int soluong = 1;
                    Add_GioHang(tensp, dongia, soluong);

                }
                if (Session["GioHang"] == null)
                {
                    Response.Redirect("~/Index.aspx");
                }
                tbGioHang = (DataTable)Session["GioHang"];
                //tbGioHang = (DataTable)Session["GioHang"];

                GVListSanpham.DataSource = tbGioHang;
                GVListSanpham.DataBind();
                GVListSanpham.FooterRow.Cells[2].Text = "Tổng tiền";
                GVListSanpham.FooterRow.Cells[3].Text = int.Parse(tbGioHang.Compute("Sum(ThanhTien)", "").ToString()).ToString("#,###,###");
            }
            catch (Exception e)
            {
                Response.Redirect("~/Index.aspx");
            }
        }



        //Thêm hàng vào gridview gio hang
        public void Add_GioHang(string TenSP, int DonGia, int SoLuong)
        {
            DataTable dt;
            if (Session["GioHang"] == null)
            {
                dt = new DataTable();
                dt.Columns.Add("TenSP");
                dt.Columns.Add("DonGia");
                dt.Columns.Add("SoLuong");
                dt.Columns.Add("ThanhTien");

            }
            else
                dt = (DataTable)Session["GioHang"];

            //int dong = SoLuongOfGioHang(TenSP, dt);
            //if (dong != -1)
            //{
            //    dt.Rows[dong]["SoLuong"] = Convert.ToInt32(dt.Rows[dong]["SoLuong"]) + SoLuong;
            //}
            
                DataRow dr = dt.NewRow();
                dr["TenSP"] = TenSP;
                dr["DonGia"] = DonGia;
                dr["SoLuong"] = SoLuong;
                dr["ThanhTien"] = DonGia * SoLuong;
                dt.Rows.Add(dr);
            
            Session["GioHang"] = dt;
        }

        //public static int SoLuongOfGioHang(string TenSP, DataTable dt)
        //{
        //    int dong = -1;
        //    for (int i = 0; i < dt.Rows.Count; i++)
        //    {
        //        if (dt.Rows[i]["TenSP"].ToString() == TenSP)
        //        {
        //            dong = i;
        //            break;
        //        }
        //    }
        //    return dong;
        //}

        public void get_ngay()
        {
            string date = DateTime.Now.ToString("dd/MM/yyyy HH:mm");
            tbNgay.Text = date;
            tbNgay.Enabled = false;
        }

        protected void GVListSanpham_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            tbGioHang = Session["GioHang"] as DataTable;
            tbGioHang.Rows.RemoveAt(e.RowIndex);
            GVListSanpham.DataSource = null;
            load_ListSanpham();
            
        }

        protected void btDelGH_Click(object sender, EventArgs e)
        {
            Session["GioHang"] = null;
            Response.Redirect("~/Index.aspx");
        }

        protected void btUpdateGH_Click(object sender, EventArgs e)
        {
            try
            {
                DataTable dt = (DataTable)Session["GioHang"];
                foreach (GridViewRow r in GVListSanpham.Rows)
                {
                    foreach (DataRow dr in dt.Rows)
                    {

                        if (GVListSanpham.DataKeys[r.RowIndex].Value.ToString().Trim() == dr["TenSP"].ToString().Trim())
                        {
                            TextBox t = (TextBox)r.Cells[2].FindControl("txtSoLuong");
                            if (Convert.ToInt32(t.Text) <= 0)
                                dt.Rows.Remove(dr);
                            else
                                dr["SoLuong"] = t.Text;
                           // break;
                        }   
                    }  
                }
                Session["Giohang"] = dt;

                GVListSanpham.DataSource = null;
                load_ListSanpham();
            }
            catch (Exception)
            {
                Response.Write("<script>alert('Đã Phát Sinh Lỗi, Vui Lòng Kiểm Tra Lại!...')</script>");
            }
        }

        protected void btSubmitGH_Click(object sender, EventArgs e)
        {
            DataAccess da = new DataAccess();
            if (Session["GioHang"] == null)
            {
                Response.Redirect("~/GioHangRong.aspx");
            }

            //Insert vào DonDatHang
            String sql1 = String.Empty;
            sql1 += String.Format(@"insert into DonDatHang(Ngay, TenKH, DiaChi, SoDT, Email) 
                    values('{0}', N'{1}', N'{2}', '{3}', N'{4}')",
                    tbNgay.Text.ToString().Trim(),
                    tbTenKH.Text.ToString().Trim(),
                    tbDiaChi.Text.ToString().Trim(),
                    tbSoDT.Text.ToString().Trim(),
                    tbEmail.Text.ToString().Trim());
            sql1 += " ; ";

            if (sql1 != String.Empty)
            {
                da.ExecuteNonQuery(sql1);
            }

            //Lấy MaDDH
            String sql2 = String.Empty;
            sql2 += String.Format(@"select MaDDH from DonDatHang where TenKH = N'{0}' and Ngay = '{1}'",
                    tbTenKH.Text.ToString().Trim(),
                    tbNgay.Text.ToString().Trim());
            sql2 += " ; ";

            string MaDDH = da.GetDataTable(sql2).Rows[0][0].ToString();

            //Insert vào ChiTietDDH
            if (tbGioHang.Rows.Count > 0)
            {
                foreach (DataRow r in tbGioHang.Rows)
                {
                    //Lấy MaSP
                    String sql3 = String.Empty;
                    sql3 += String.Format(@"select MaSP from SanPham where TenSP = N'{0}' and DonGia = {1}",
                            r["TenSP"].ToString(),
                            int.Parse(r["DonGia"].ToString()));
                    sql3 += " ; ";

                    string MaSP = da.GetDataTable(sql3).Rows[0][0].ToString();

                    //Insert
                    String sql4 = String.Empty;

                    sql4 += String.Format(@"insert into ChiTietDDH values({0}, '{1}', {2})",
                            int.Parse(MaDDH),
                            MaSP,
                            int.Parse(r["SoLuong"].ToString()));
                    sql4 += " ; ";
                    
                    if (sql4 != String.Empty)
                    {
                        da.ExecuteNonQuery(sql4);
                    }
                }
            }

            Session["GioHang"] = null;
            da.Close();
            Response.Redirect("~/DHThanhCong.aspx");
            
        }

    }
}